
import Head from 'next/head'

<Head>
  <script>
    {
      `(function() {
         var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?e60fb290e204e04c5cb6f79b0ac1e697";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
       })();`
    }
  </script>
</Head>

![LangChain](https://pica.zhimg.com/50/v2-56e8bbb52aa271012541c1fe1ceb11a2_r.gif)





Tair[#](#tair "Permalink to this headline")
===========================================

本笔记展示如何使用与Tair向量数据库相关的功能。
要运行，请确保已经启动了[Tair](https://www.alibabacloud.com/help/zh/tair/latest/what-is-tair)实例。

```python
from langchain.embeddings.fake import FakeEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import Tair

```

```python
from langchain.document_loaders import TextLoader
loader = TextLoader('../../../state_of_the_union.txt')
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
docs = text_splitter.split_documents(documents)

embeddings = FakeEmbeddings(size=128)

```

使用`TAIR_URL`环境变量或关键字参数`tair_url`连接到Tair。

```python
export TAIR_URL="redis://{username}:{password}@{tair_address}:{tair_port}"

```

然后将文档和嵌入存储到Tair中。

查询相似的文档。

```python
tair_url = "redis://localhost:6379"

# drop first if index already exists
Tair.drop_index(tair_url=tair_url)

vector_store = Tair.from_documents(
    docs,
    embeddings,
    tair_url=tair_url
)

```

查询相似的文档。

```python
query = "What did the president say about Ketanji Brown Jackson"
docs = vector_store.similarity_search(query)
docs[0]

```

```python
Document(page_content='We’re going after the criminals who stole billions in relief money meant for small businesses and millions of Americans.    And tonight, I’m announcing that the Justice Department will name a chief prosecutor for pandemic fraud.   By the end of this year, the deficit will be down to less than half what it was before I took office.    The only president ever to cut the deficit by more than one trillion dollars in a single year.   Lowering your costs also means demanding more competition.   I’m a capitalist, but capitalism without competition isn’t capitalism.   It’s exploitation—and it drives up prices.   When corporations don’t have to compete, their profits go up, your prices go up, and small businesses and family farmers and ranchers go under.   We see it happening with ocean carriers moving goods in and out of America.   During the pandemic, these foreign-owned companies raised prices by as much as 1,000% and made record profits.', metadata={'source': '../../../state_of_the_union.txt'})

```

